package com.shuangk.majingze.coolpapa.http;


import android.content.Context;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shuangk.majingze.coolpapa.http.apiservice.CoolService;
import com.shuangk.majingze.coolpapa.model.User;
import com.shuangk.majingze.coolpapa.model.UserInfoVo;

import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class RetrofitClient {

    private static RetrofitClient retrofitClient;

    private static final int CONNECTION_TIME_OUT = 15;
    private static final int READ_TIME_OUT = 15;

    private OkHttpClient okHttpClient;
    private CoolService apiService;
    private Context mContext;
    private String baseUrl;

    private RetrofitClient(Context context) {
        this(context, null);
    }

    private RetrofitClient(Context context, String baseUrl) {
        if (StringUtils.isBlank(baseUrl)) {
            this.baseUrl = RequestUrl.BASE_URL;
        }else {
            this.baseUrl = baseUrl;
        }
        okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(this.baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
        apiService = retrofit.create(CoolService.class);
    }

    public synchronized static RetrofitClient getInstance(Context context) {
        if (retrofitClient == null) {
            retrofitClient = new RetrofitClient(context);
        }
        return retrofitClient;
    }

    public static RetrofitClient getInstance(Context context, String baseUrl) {
        return new RetrofitClient(context, baseUrl);
    }

    public  CoolService getService(){
        return apiService;
    }
}
